package com.qy.controller.app;

import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.weixin.utils.PayCommonUtil;
import com.qy.base.utils.weixin.utils.WXAPPConfigUtil;
import com.qy.model.Member;
import com.qy.model.MemberOrder;
import com.qy.model.RewardOrder;
import com.qy.model.Toll;
import com.qy.service.MemberOrderService;
import com.github.pagehelper.PageHelper;
import com.qy.service.MemberService;
import com.qy.service.TollService;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.util.*;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController
@RequestMapping("app/member/order")
public class MemberOrderController {
    @Resource
    private MemberOrderService memberOrderService;

    @Resource
    private TollService tollService;

    @Resource
    private MemberService memberService;

    @PostMapping("/add")
    public Result add(@RequestBody MemberOrder memberOrder) {
        memberOrderService.save(memberOrder);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        memberOrderService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody MemberOrder memberOrder) {
        memberOrderService.update(memberOrder);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        MemberOrder memberOrder = memberOrderService.findById(id);
        return ResultGenerator.successResult(memberOrder);
    }

    @GetMapping("/list")
    public Result list(PageBean<MemberOrder> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<MemberOrder> list = memberOrderService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //会员收费价格
    @GetMapping("/memberPrice")
    public Result memberPrice() {
        List<Toll> list = tollService.selectMemberPrice();
        return ResultGenerator.successResult(list);
    }

    //会员支付
    @PostMapping("/memberPay")
    public Result memberPay(@RequestBody MemberOrder memberOrder, HttpServletRequest request) throws Exception {
        if (memberOrder.getUser_id() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        Member member = memberService.findById(memberOrder.getUser_id());
        //调起支付
        Random random = new Random();
        String content = String.valueOf(random.nextInt(9999) % (9999 - 1000 + 1) + 1000);
        String randomOrderNum = DateUtil.getNowTimestamp() + content;
        //准备商家数据包
        HashMap<String, Object> attachMap = new HashMap<>();
        attachMap.put("user_id", memberOrder.getUser_id());
        attachMap.put("bars_number", memberOrder.getBars_number());
        SortedMap<Object, Object> resultMap = PayCommonUtil.wxPay(WXAPPConfigUtil.APPID, WXAPPConfigUtil.MCH_ID, randomOrderNum, Double.valueOf(memberOrder.getAmount()), member.getWechat_id(), "充值会员", "JSAPI", "", JSONObject.fromObject(attachMap).toString(), WXAPPConfigUtil.MEMBER_PAY_NOTIFY_URL, request);

        return ResultGenerator.successResult(resultMap);
    }

    //会员支付回调
    @RequestMapping("/memberPayNotify")
    public void memberPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map packageParams = PayCommonUtil.getWXNotifyData(request, WXAPPConfigUtil.API_KEY);
        String resXml = "";
        if (packageParams != null) {
            //------------------------------
            //处理业务开始
            //------------------------------

            FileWriter writer = new FileWriter(Constants.PATH_IMAGE_PATH + "wx_notify.txt", true);

            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                // 这里是支付成功
                //////////执行自己的业务逻辑////////////////

                try {
                    Double money = Double.valueOf((String) packageParams.get("total_fee")) / 100;
                    String randomOrderNum = (String) packageParams.get("out_trade_no");
                    String attach = (String) packageParams.get("attach");
                    JSONObject attachObj = JSONObject.fromObject(attach);
                    String user_id = attachObj.getString("user_id");
                    String bars_number = attachObj.getString("bars_number");

                    Member member = memberService.findById(Integer.valueOf(user_id));
                    member.setMember_surplus_number(member.getMember_surplus_number() + Integer.valueOf(bars_number));
                    memberService.update(member);
                    MemberOrder memberOrder = new MemberOrder();
                    memberOrder.setUser_id(member.getId());
                    memberOrder.setOrder_number(randomOrderNum);
                    memberOrder.setName(member.getName());
                    memberOrder.setPhone(member.getPhone());
                    memberOrder.setAmount(money.toString());
                    memberOrder.setBars_number(bars_number);
                    memberOrder.setAdd_time(DateUtil.getNowTimestamp());
                    memberOrderService.save(memberOrder);
                } catch (Exception e) {
                    writer.write(e.toString());
                    writer.flush();
                    writer.close();
                }

                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                resXml = PayCommonUtil.setXML("SUCCESS", "OK");

            } else {
                resXml = PayCommonUtil.setXML("FAIL", "报文为空");
            }
        } else {
            resXml = PayCommonUtil.setXML("FAIL", "报文为空");
        }
        //------------------------------
        //处理业务完毕
        //------------------------------
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }
}
